//
//  MNDLatestReturnWebViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/9/26.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDLatestReturnWebViewController.h"
#import "SYWebLoadingProgress.h"
#import "RSAUtil.h"

@interface MNDLatestReturnWebViewController ()

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@property(nonatomic, strong) SYWebLoadingProgress *webLoadingProgress;

@end

@implementation MNDLatestReturnWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", BroswerHeadURL, [NSString urlEncodeStr:self.url]];
    NSURLRequest *request = [self configRequestHeaderFileds:[NSURL URLWithString: urlStr]];
    [self.webView loadRequest:request];
    [self.view beginLoading];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSMutableURLRequest *)configRequestHeaderFileds: (NSURL *)url {
    // 添加请求头信息
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];
    
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    NSString *userCode = [self rsaEncode: user.user_code];
    
    [request setValue:userCode forHTTPHeaderField:@"USERCODE"];
    
    return request;
}

- (NSString *)rsaEncode:(NSString *)rsaStr {
    NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", rsaStr] publicKey:RSA_PUBLIC_KEY];
    NSString *unreserved = @"";
    NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
    [allowed addCharactersInString:unreserved];
    
    NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
    
    return encodeEncryText;
}

- (NSMutableURLRequest *)addHTTPHeaderFieldWithRequest:(NSURLRequest *)request {
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    //来源加入header
    if (kDevice_iPad) {
        [mutableRequest addValue:@"iPad" forHTTPHeaderField:@"WERTYUIOP"];
    } else {
        [mutableRequest addValue:@"iPhone" forHTTPHeaderField:@"WERTYUIOP"];
    }
    
    return mutableRequest;
}

#pragma mark - UIWebView Delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSMutableURLRequest *mutableRequest = [self addHTTPHeaderFieldWithRequest:request];
    request = [mutableRequest copy];
    
    return YES;
}

- (SYWebLoadingProgress *)webLoadingProgress {
    if (!_webLoadingProgress) {
        _webLoadingProgress = [[SYWebLoadingProgress alloc] init];
        _webLoadingProgress.progressColor = kColorBlue;
        _webLoadingProgress.progressStyle = LoadingPregressType_Noraml;
    }
    
    if ([self.navigationController.navigationBar isHidden]) {
        _webLoadingProgress.frame = CGRectMake(0, 20, kScreenWidth, 2);
        
    } else {
        CGFloat yPosition = 64.0;
        if (kScreenHeight >= 812) {
            yPosition = 88;
        }
        _webLoadingProgress.frame = CGRectMake(0, yPosition, kScreenWidth, 2);
        //        [self.view.layer insertSublayer:_webLoadingProgress atIndex:0];
    }
    [self.webView.layer addSublayer:_webLoadingProgress];
    
    return _webLoadingProgress;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    [self.webLoadingProgress startProgressAnimation];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    //    取消长按webView上的链接弹出actionSheet的问题
    [webView stringByEvaluatingJavaScriptFromString: @"document.documentElement.style.webkitUserSelect='none';"];
    if ([webView.request.URL.absoluteString containsString:kCustomerServiceURLStr]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('chat-view-window-header-back')[0].style.display='none';"];
            self.title = @"在线客服";
        });
    }
    [self.webLoadingProgress completedProgressAnimation];
    [self.view endLoading];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [self.webLoadingProgress completedProgressAnimation];
    if (error.code == -999) {
        return;
    }
    
    if (error.code == 102 || error.code == -102) {
        return;
    }
    
    [NetworkProgressHUD showHudNetworkError:error];
    WeakSelf(self);
    SYBlankPageType blankType = [weakself.view blankPageTypeWithError:error];
    [self.view configBlankPage:blankType hasData:NO reloadButtonBlock:^(id sender) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakself.webView reload];
            //            [weakself.view beginLoading];
        });
        
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
